package com.feihong.yw189.activity.yonghuzhongxin.wodexiaoxi;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;

import com.blankj.utilcode.util.AppUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.dialog.ShareBottomDialog;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.utils.UserLoginInfo;
import com.feihong.yw189.view.ZoomImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class ShareActivity extends BaseActivity {

    private ImageView mCustomIcon;
    private SaveImage saveImage;
    private String mImgUrl;
    private ShareBottomDialog mShareBottomDialog;
    private ZoomImageView mImageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.share_layout);

        ShareActivityPermissionsDispatcher.NeedsWithCheck(this);
        initView();
    }

    @Override
    public void setTheme() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    public void initView() {
        mShareBottomDialog = new ShareBottomDialog(this);
        saveImage = new SaveImage();
        mCustomIcon = findViewById(R.id.iv_lin);
        mCustomIcon.setVisibility(View.GONE);
        mImageView = findViewById(R.id.share_image_layout);
        setBackButtonFinish();
        setPageTitle("分享二维码");
        mImgUrl  = HttpTools.SHARE_ACTIVITY + "?token=" + UserLoginInfo.getUserLoginInfoInstance().getUserToken() + "&version=" + "and." + AppUtils.getAppVersionName();
        Glide.with(this).asBitmap().load(mImgUrl).into(mImageView);
        mImageView.setOnClickListener(v -> mShareBottomDialog.showDialog());
        mShareBottomDialog.setOperateListener(() -> {
            mShareBottomDialog.cancel();
            showToast("正在保存");
            new SaveImage().execute();
        });

    }


    @OnClick(R.id.iv_confirm)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_confirm:
                startActivity(new Intent(ShareActivity.this, ShouYiActivity.class));
                break;
            default:
                break;
        }
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Needs() {
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ShareActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void OnShowRationale(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", (dialog, which) ->  request.proceed())
                .setNegativeButton("拒绝", (dialog, which) -> request.cancel())
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Denied() {
        showErrorDialog("权限不足", "您没有开启此应用的使用文件存储权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下存储权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void AskAgain() {
        showErrorDialog("权限不足", "您没有开启此应用的使用文件存储权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下存储权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    /***
     * 功能：用线程保存图片
     * @author wangyp
     */
    public class SaveImage extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            InputStream inputStream = null;
            FileOutputStream outStream = null;
            String result;
            try {
                String sdcard = ShareActivity.this.getFilesDir().getAbsolutePath();
                File file = new File(sdcard + File.separator + "shareImg" + ".jpg");
                URL url = new URL(mImgUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20000);
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                }else {
                    return "下载失败";
                }
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                outStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,outStream);
                try {
                    MediaStore.Images.Media.insertImage(ShareActivity.this.getContentResolver(),
                            file.getAbsolutePath(), file.getName(), null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
//                // 最后通知图库更新
                ShareActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(new File(file.getPath()))));
                result = "保存成功";
            } catch (Exception e) {
                result = "保存失败！" + e.getLocalizedMessage();
            }finally {
                if(outStream != null){
                    try {
                        outStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            showToast(result);
        }
    }



}
